//
//  DrinkReminderView.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/8/24.
//

import SwiftUI

struct DrinkRecords: Identifiable, Hashable {
    let id = UUID()
    var value: Int
    var time: String
}

struct DrinkReminderView: View {
    @State private var selectedDate: Date = Date()
    
    @State private var showAddRecord = false
    
    @State var records: [DrinkRecords] = [
//        DrinkRecords(value: 200, time: "上午 10:02"),
//        DrinkRecords(value: 400, time: "下午 01:30"),
//        DrinkRecords(value: 800, time: "下午 05:16"),
//        DrinkRecords(value: 500, time: "下午 07:16")
    ]
    
    var body: some View {
        GeometryReader { geo in
            VStack {
                CustomNavigationBar(rightImageName: nil, title: "饮水提醒") {}
                HStack {
                    WeekdayPicker(backGroundColor: Color(hex: "#EF5F5F")) { Date in
                        print(Date)
                        selectedDate = Date
                    }
                    Image("日历 1")
                        .resizable()
                        .frame(width: 20,height: 20)
                        .onTapGesture {
                            
                        }
                }
                .padding(.horizontal,12)
                
                ScrollView(.vertical,showsIndicators: false) {
                    VStack(spacing: 0) {
                        HStack {
                            Text("健康摄入量目标")
                                .font(.system(size: 16))
                                .foregroundStyle(.white)
                                .padding(.leading,12)
                            Spacer()
                            Text("2000ml")
                                .font(.system(size: 16))
                                .foregroundStyle(.white)
                                .padding(.trailing,20)
                        }
                        .frame(height: 56)
                        .background(Color(hex: "#1E1E1E"))
                        .cornerRadius(16)
                        .padding(.horizontal,12)
                        
                        StaticWaveCupView(waterLevel: 0.7)
                            .padding(.top, 24)
                        HStack {
                            Button(action: {
                                showAddRecord = true
                            }, label: {
                                Text("添加记录")
                                    .frame(width: 160, height: 40)
                                    .font(.system(size: 16, weight: .medium))
                                    .foregroundColor(Color(hex: "#242424"))
                                    .background(LinearGradient(colors: [
                                        Color(hex: "#A5F4F5"),
                                        Color(hex: "#6FE4E6"),
                                        Color(hex: "#34D3D5"),
                                    ], startPoint: .leading, endPoint: .trailing))
                                    .cornerRadius(11.0)
                            })
                        }
                        .padding(.top, 20 + 254)
                        if records.isEmpty == false {
                            ZStack {
                                Color(hex: "#1E1E1E")
                                    .cornerRadius(16)
                                VStack(alignment: .leading) {
                                    HStack(spacing: 0) {
                                        Text("饮水记录")
                                            .font(.system(size: 16))
                                            .foregroundStyle(.white)
                                        Spacer()
                                    }
                                    .padding(.bottom, 16)
                                    ForEach(Array(records.enumerated()), id: \.element.id) { index, record in
                                        VStack {
                                            HStack {
                                                Image("drink_record_list")
                                                    .frame(width: 24, height: 24)
                                                Text("\(record.value)ml")
                                                    .font(.system(size: 16, weight: .regular))
                                                    .foregroundColor(.white)
                                                    .padding(.leading, 12)
                                                Spacer()
                                                Text("\(record.time)")
                                                    .font(.system(size: 16, weight: .regular))
                                                    .foregroundColor(.white)
                                                    .padding(.leading, 12)
                                            }
                                            if index < records.count - 1 {
                                                Divider()
                                                    .background(Color(hex: "#656565"))
                                                    .padding(.vertical, 12)
                                            }
                                        }
                                    }
                                }
                                .padding(.all, 20)
                                
                            }
                            .padding(.top, 24)
                            .padding(.horizontal, 12)
                        }
                        
                    }
                    .padding(.bottom, geo.safeAreaInsets.bottom)
                    
                    
                }
                .padding(.top, 10)
                Spacer()
            }
            .navigationBarHidden(true)
            .background(Color(hex: "#0A0A0A"))
            .edgesIgnoringSafeArea(.all)
        }
        .sheet(isPresented: $showAddRecord) {
            AddRecordsView(showAddRecord: $showAddRecord) { intake in
                let now = Date()
                let formatter = DateFormatter()
                formatter.dateFormat = "a hh:mm"
                formatter.amSymbol = "上午"
                formatter.pmSymbol = "下午"
                let timeString = formatter.string(from: now)
                records.append(DrinkRecords(value: intake, time: timeString))
                print("===", records)
            }
            .presentationDetents([.height(216)])
            .presentationBackground(Color(hex: "#1E1E1E"))
            .presentationCornerRadius(20)
            .ignoresSafeArea()
        }
        .dismissingKeyboard()
    }
}



struct StaticWaveCupView: View {
    let waterLevel: Double
    
    func effectiveLevel(_ level: Double) -> Double {
        if (level == 1) {
            return level
        } else {
            let t = 1 - level
            let eased = 1 - pow(t, 2)
            return eased * 0.75
        }
    }
    
    var body: some View {
        GeometryReader { geo in
            ZStack {
                Image("empty_cup")
                    .resizable()
                    .frame(width: 180, height: 254)
                    .aspectRatio(contentMode: .fit)
                
                StaticWaveShape(level: effectiveLevel(waterLevel),
                                amplitude: 8,
                                frequency: 0.008,
                                phase: .pi)
                    .fill(
                        LinearGradient(
                            colors: [Color(hex: "#BBF6F0"), Color(hex: "#C7F6F4")],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .aspectRatio(contentMode: .fit)
                    .mask(
                        Image("empty_cup")
                            .resizable()
                            .frame(width: 178, height: 254)
                            .aspectRatio(contentMode: .fit)
                    )
                
                StaticWaveShape(level: effectiveLevel(waterLevel),
                                amplitude: 8,
                                frequency: 0.008,
                                phase: 0)
                    .fill(
                        LinearGradient(
                            colors: [Color(hex: "#28D0D2"), Color(hex: "#A8F5F6"), Color(hex: "#62DCDD")],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .aspectRatio(contentMode: .fit)
                    .mask(
                        Image("empty_cup")
                            .resizable()
                            .frame(width: 178, height: 254)
                            .aspectRatio(contentMode: .fit)
                    )
                
                GeometryReader { innerGeo in
                    let eff = effectiveLevel(waterLevel)
                    let centerY = innerGeo.size.height * (1 - eff / 2)

                    Text("1225ml")
                        .font(.system(size: 34, weight: .medium))
                        .frame(height: 34)
                        .foregroundColor(Color(hex: "#076E70"))
                        .position(x: innerGeo.size.width / 2, y: centerY - 17)
                }
                .frame(width: 180, height: 254)
                
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }
}

private struct StaticWaveShape: Shape {
    let level: Double
        let amplitude: CGFloat
        let frequency: CGFloat
        let phase: Double
        
    func path(in rect: CGRect) -> Path {
        var p = Path()
        let baseY = rect.maxY - CGFloat(level) * rect.height
        
        p.move(to: CGPoint(x: 0, y: baseY))
        for x in stride(from: 0, through: rect.width, by: 1) {
            let y = amplitude * sin(x * frequency * 2 * .pi + phase)
            p.addLine(to: CGPoint(x: x, y: baseY + y))
        }
        p.addLine(to: CGPoint(x: rect.width, y: rect.maxY))
        p.addLine(to: CGPoint(x: 0, y: rect.maxY))
        p.closeSubpath()
        return p
    }
}

struct AddRecordsView: View {
    @Binding var showAddRecord: Bool
    @State private var waterIntakeText: String = ""
    private var waterIntake: Int? {
        Int(waterIntakeText)
    }
    let onAddRecord: (Int) -> Void
    
    var body: some View {
        VStack(spacing: 0) {
            HStack {
               Text("添加记录")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(.white)
                Spacer()
                Button(action: {
                    showAddRecord = false
                }) {
                    Image("close")
                        .frame(width: 16, height: 16)
                }
            }
            .padding(.top, 20)
            .padding(.horizontal, 20)
            
            ZStack(alignment: .leading) {
                Color(hex: "#F7F8FA")
                    .frame(height: 46)
                    .cornerRadius(12)
                if waterIntakeText.isEmpty {
                    Text("请输入饮水量（单位：ml）")
                        .font(.system(size: 16, weight: .regular))
                        .padding(.horizontal, 16)
                        .foregroundColor(Color (hex: "#999999"))
                }
                TextField("", text: $waterIntakeText)
                    .font(.system(size: 16))
                    .keyboardType(.numberPad)
                    .frame(height: 44)
                    .padding(.horizontal, 16)
                    .foregroundColor(Color.black)
                    .autocapitalization(UITextAutocapitalizationType/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
                
                
            }
            .padding(.top, 32)
            .padding(.horizontal, 20)
            
            Button {
                if let intake = waterIntake, intake > 0 {
                    onAddRecord(intake)
                    showAddRecord = false
                }
            } label: {
                Text("添加")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Color(hex: "#242424"))
                    .frame(maxWidth: .infinity, alignment: .center)
                    .frame(height: 44)
                    .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing))
                    .cornerRadius(22)
            }
            .padding(.top, 32)
            .padding(.horizontal, 20)
            
            Spacer()
        }
    }
}



// MARK: - 预览
struct StaticWaveCupView_Previews: PreviewProvider {
    static var previews: some View {
        StaticWaveCupView(waterLevel: 0.9)
    }
}


